package com.oazon.moco.lan.core.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.util.CharsetUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.util.Log;

import com.oazon.moco.lan.core.http.bean.JsonRequest;
import com.oazon.moco.lan.core.http.bean.JsonResponse;
import com.oazon.moco.lan.util.UrlDecode;

public class HttpJsonRequestDecoder extends AbsHttpJsonDecoder<FullHttpRequest> {

	private static final String TAG = "HttpJsonRequestDecoder";

	public HttpJsonRequestDecoder(Class<?> clazz) {
		super(clazz);
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, FullHttpRequest request,
			List<Object> out) throws Exception {
		HttpJsonRequest req = null;

		if (!request.getDecoderResult().isSuccess()) {
			sendError(ctx, HttpResponseStatus.BAD_REQUEST);
			return;
		}
		Log.d(TAG, request.getUri() + "===========" + request.getMethod());
		try {
			req = new HttpJsonRequest(request, FullHttpRequestDecode(request));
		} catch (Exception e) {
			if(e.getMessage()!=null){
				Log.e(TAG, "uriDecode" + e.getMessage());
				req = new HttpJsonRequest(request, e.getMessage());
			}else{
				req = new HttpJsonRequest(request, e.getCause());
			}
		}
		out.add(req);
	}
	private static void sendError(ChannelHandlerContext ctx,
			HttpResponseStatus status) {
		FullHttpResponse response = new DefaultFullHttpResponse(
				HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: "
						+ status.toString() + "\r\n", CharsetUtil.UTF_8));
		response.headers().set(HttpHeaders.Names.CONTENT_TYPE,
				"text/plain; charset=UTF-8");
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}

	private Object FullHttpRequestDecode(FullHttpRequest request) {
		Object jsonMsg = null;
		try {
			String operation = "";
			String classification = "";
			Map<String, String> map = new HashMap<String, String>();

			String root = null;
			String uri = request.getUri();
			if (uri.indexOf("?") < 0) {
				root = uri;
			} else {
				root = uri.split("[?]")[0];
			}

			String[] roots = root.split("[/]");

			if (roots.length > 1) {
				operation = roots[1].replaceAll("[/]", "");
			}
			if (roots.length > 2) {
				classification = roots[2].replaceAll("[/]", "");
			}

			if (request.getMethod() == HttpMethod.GET) {
				UrlDecode.parseParameters(map, uri, "UTF-8");
			}
			if (request.getMethod() == HttpMethod.POST) {
				UrlDecode.parseParameters(request, map);
			}

			if (roots.length > 1) {
				jsonMsg = new JsonRequest();

				((JsonRequest) jsonMsg).setOperation(operation);
				((JsonRequest) jsonMsg).setClassification(classification);
				((JsonRequest) jsonMsg).setType(map.get("type"));
				((JsonRequest) jsonMsg).setUuid(map.get("uuid"));

				if (map.get("data") != null) {
					if (request.getMethod() == HttpMethod.GET) {
						((JsonRequest) jsonMsg).setData(URLDecoder.decode(
								map.get("data"), "utf-8"));
					} else {
						((JsonRequest) jsonMsg).setData(map.get("data"));
					}
				}

			} else {
				jsonMsg = new String("没有准确的路径");
			}

		} catch (Exception e) {
			jsonMsg =  new String(e.getCause().toString());
		}

		return jsonMsg;
	}

}
